<template>
  <el-card class="edit" shadow="never">
    <template #header>
      <div class="edit-title">用户信息</div>
      <div class="edit-desc">
        {{ $route.path.indexOf("user/add") !== -1 ? "添加" : "修改" }}
      </div>
    </template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100"
      size="large"
    >
      <el-form-item label="所属机构" prop="orgId">
        <Select
          v-model="form.orgId"
          url="org/listpage"
          :params="{ state: 1 }"
          search-parm-name="name"
          option-label="name"
          option-value="id"
          :multiple="false"
          :options="orgs"
          placeholder="请选择机构"
        >
          <template #default="{ option }">
            {{ option.name }} - {{ option.parentName }}
          </template>
        </Select>
      </el-form-item>
      <el-form-item label="标签" prop="labelId">
        <el-select v-model="form.labelId">
          <el-option
            v-for="item in labels"
            :key="item.id"
            :value="item.id + ''"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex">
          <el-option
            v-for="item in sexes"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="身份证" prop="loginName">
        <el-input
          v-model="form.loginName"
          placeholder="请输入登录账号:身份证号"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入电话号码" />
      </el-form-item>

      <el-form-item>
        <el-button
          v-if="$route.path.indexOf('user/add') !== -1"
          type="primary"
          @click="add"
        >
          添加
        </el-button>
        <el-button v-else type="primary" @click="edit"> 修改 </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import http from "@/request/index";
import { useRouter, useRoute } from "vue-router";
import Select from "@/components/Select.vue";
import type { User, Org } from "@/ts";

// 定义变量
const labels = ref([]);
const sexes = [
  {
    value: "1",
    label: "男",
  },
  {
    value: "2",
    label: "女",
  },
];
const route = useRoute();
const router = useRouter();
const form = reactive({
  // 表单
  type: 1,
  orgId: null,
  labelId: null,
  sex: null,
} as User);
const orgs = ref([] as Org[]);
const formRef = ref<FormInstance>(); // 表单引用
const checkCardId = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入身份证号作为登录账户"));
  } else {
    const id_pattern = /^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;

    if (!id_pattern.test(value)) {
      callback(new Error("请输入正确的身份证号"));
    }
    callback();
  }
};
const checkPhone = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else {
    const id_pattern =
      /^((13[0-9])|(14[5,7,9])|(15[^4])|(16[6])|(17[0-8])|(18[0-9])|(19[1,8,9]))\d{8}$/;

    if (!id_pattern.test(value)) {
      callback(new Error("请输入正确的手机号"));
    }
    callback();
  }
};
const formRules = reactive<FormRules>({
  orgId: [{ required: true, message: "请选择机构", trigger: "blur" }],
  // 表单校验规则
  loginName: [
    { validator: checkCardId, trigger: "blur" },
    { required: true, message: "请输入登录账号:身份证号", trigger: "blur" },
    /* { min: 1, max: 18, message: "长度介于1-18", trigger: "blur" }, */
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 1, max: 8, message: "长度介于1-8", trigger: "blur" },
  ],
  labelId: [{ required: true, message: "请选择标签", trigger: "blur" }],
  phone: [
    { validator: checkPhone, trigger: "blur" },
    { required: true, message: "请输入登录账号:身份证号", trigger: "blur" },
  ],
});

const getLabels = async () => {
  try {
    const res = await http.post("label/listpage", {
      curPage: 1,
      pageSize: 10,
    });
    console.log(res.data.data.total);
    console.log(res.data.data.list);
    labels.value = res.data.data.list;
  } catch (error) {
    console.log(error);
  }
};
// 组件挂载完成后，执行如下方法
onMounted(async () => {
  getLabels();
  if (route.path.indexOf("user/add") !== -1) {
    console.log("");
  } else {
    // 修改
    let {
      data: { data },
    } = await http.post("user/get", { id: route.params.id });
    form.id = data.id;
    form.name = data.name;
    form.labelId = data.labelId;
    form.loginName = data.loginName;
    form.orgId = data.orgId;
    form.sex = data.sex;
    form.phone = data.phone;
    let res = await http.post("org/get", { id: form.orgId });
    orgs.value.push(res.data.data);
  }
});

// 添加
async function add() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }

    let {
      data: { code, data },
    } = await http.post("user/add", {
      loginName: form.loginName,
      name: form.name,
      orgId: form.orgId,
      type: form.type,
      labelId: form.labelId,
      sex: form.sex,
      phone: form.phone,
    });

    if (code !== 200) {
      return;
    }
    ElMessage({
      message: `密码初始化：${data.initPwd}`,
      type: "success",
      duration: 0,
      showClose: true,
    });
    router.push("/user");
  });
}

// 修改
async function edit() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }

    let {
      data: { code, data },
    } = await http.post("user/edit", {
      id: form.id,
      loginName: form.loginName,
      name: form.name,
      orgId: form.orgId,
      type: form.type,
      labelId: form.labelId,
      sex: form.sex,
      phone: form.phone,
    });

    if (code !== 200) {
      return;
    }
    if (data?.initPwd) {
      ElMessage({
        message: `密码初始化：${data.initPwd}`,
        type: "success",
        duration: 0,
        showClose: true,
      });
    }

    router.push("/user");
  });
}
</script>

<style lang="scss" scoped>
.edit {
  padding: 10px;
  height: calc(100vh - 300px);

  :deep(.el-card__header) {
    padding-bottom: 0px;

    .edit-title {
      font-size: 14px;
      font-weight: bold;
      padding-bottom: 5px;
    }

    .edit-desc {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
